<template>
	 <view class="go-back">
	 	<view git class="back-icon" @click="goBack"></view>
	 	<view class="title">宠物档案</view>
	 </view>
 	<view class="cwdn-container">
		<view class="dn-head">
			<view class="dn-tag"></view>
		</view>
		<view class="form-container">
			<view class="form-box">
				<view class="form-item" style="border-bottom:none;">
					<text class="name">宠物类型</text>
					<view class="radio-list">
						<view class="radio-item" :class="{'radio-active': formData.type == item.value}"
							v-for="(item, index) in petTypes" :key="item.value" @click="formData.type = item.value">
							<view class="radio-mark">
								<uni-icons v-if="formData.type == item.value" type="checkmarkempty" :size="12" color="#fff"></uni-icons>
							</view>
							<view>{{ item.text }}</view>
						</view>
					</view>
				</view>
				<view class="form-item">
					<text class="name">宠物名称</text>
					<text class="note" style="color: red;">(必填)</text>
					<input class="ipt" type="text" v-model="formData.nickname" placeholder="请填写宠物名称" />
				</view>
				<view class="form-item">
					<text class="name">出生日期</text>
					<picker class="ipt" mode="date" :value="formData.birthday" :start="startDate" :end="endDate" @change="bindDateChange">
						<view class="uni-input">{{formData.birthday}}</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="name">宠物性别</text>
					<text class="note" style="color: red;">(必填)</text>
					<picker  class="ipt" @change="bindPickerChange" :value="sexIndex" :range="sexArr">
						<view class="uni-input" v-if="formData.sex>0">{{ formData.sex==1?"GG":"MM" }}</view>
						<view class="uni-input" v-else>请选择性别</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="name">品种</text>
					<input class="ipt" type="text" v-model="formData.breeds" placeholder="请填写宠物品种" />
				</view>
				<view class="form-item">
					<text class="name">体重</text>
					<text class="note">(KG)</text>
					<input class="ipt" type="number" v-model="formData.weight" @input="onWeightInput" placeholder="请输入宠物体重" />
				</view>
				<view class="form-item" style="border-bottom:none;">
					<text class="name">绝育状态</text>
					<text class="note" style="color: red;">(必填)</text>
					<view class="radio-list">
						<view class="radio-item" :class="{'radio-active': formData.neuter_status == item.value}"
							v-for="(item, index) in neuterTypes" :key="item.value" @click="formData.neuter_status = item.value">
							<view class="radio-mark">
								<uni-icons v-if="formData.neuter_status == item.value" type="checkmarkempty" :size="12" color="#fff"></uni-icons>
							</view>
							<view>{{ item.text }}</view>
						</view>
					</view>
				</view>
				<view class="form-item" style="border-bottom:none;">
					<text class="name">自我介绍</text>
					<view class="text-area-wrapper">
						<textarea class="desc" v-model="formData.desc" @input="textAreaIpt" placeholder="请为您的宠物作一段自我介绍" placeholder-style="color:#787878;"></textarea>
					</view>
				</view>
				<!-- 活动图片 -->
				<view class="form-item" style="border-bottom:none;">
					<text class="name">宠物照片</text>
					<text class="note">(最多9张)</text>
					<view class="images-list">
						<view class="img-wrapper" v-for="(img, index) in images" :key="index">
							<uni-icons class="del-ico" type="minus-filled" :size="24" color="#dd524d"
								@click="delImage(index)"></uni-icons>
							<image class="img" :src="img.url" mode="aspectFill"></image>
							<view class="percent-mask" v-if="img.fail || img.progress < 100">
								<text v-if="!img.fail">{{ img.progress }}%</text>
								<text v-if="img.fail" @click="uploadAgain(index)">点击重试</text>
							</view>
						</view>
						<view class="add-btn" v-if="images.length < 9" hover-class="tap-hover" @click="addImage()">
							<uni-icons type="plusempty" :size="30" color="#02C9BF"></uni-icons>
						</view>
					</view>
				</view>
			</view>
		</view>
 	</view>
	<fixed-footer class="fixed-footer">
		<primary-btn title="提交" :disabled="btnDisabled" @btnClick="check()"></primary-btn>
	</fixed-footer>
	<uni-popup ref="checkPopup" type="center" :is-mask-click="false">
		<view class="popup-content">
			<view class="close-btn"  @click="$popupChange(this, 'checkPopup')"></view>
			<view class="info-wrapper">
				<image class="check-white" src="/static/images/check-white.svg" mode="widthFix"></image>
				<view class="info">
					<view class="info-item">
						<view class="name">宠物类型：</view>
						<view class="text">{{ formData.type ==1 ?"狗狗" :"猫猫" }}</view>
					</view>
					<view class="info-item">
						<view class="name">宠物名称：</view>
						<view class="text">{{ formData.nickname }}</view>
					</view>
					<view class="info-item">
						<view class="name">出生日期：</view>
						<view class="text">{{ formData.birthday }}</view>
					</view>
					<view class="info-item">
						<view class="name">宠物性别：</view>
						<view class="text">{{ formData.sex==1?"GG":"MM" }}</view>
					</view>
					<view class="info-item">
						<view class="name">品种：</view>
						<view class="text">{{ formData.breeds }}</view>
					</view>
					<view class="info-item">
						<view class="name">体重：</view>
						<view class="text">{{ formData.weight }}kg</view>
					</view>
					<view class="info-item">
						<view class="name">绝育状态：</view>
						<view class="text">{{ formData.neuter_status==1?"未绝育":"已绝育" }}</view>
					</view>
					<view class="info-item">
						<view class="name">自我介绍：</view>
					</view>
					<view class="desc">{{formData.desc}}</view>
				</view>
				<view class="btn-wrapper">
					<view class="left-btn" hover-class="tap-hover" @click="$popupChange(this, 'checkPopup')">修改信息</view>
					<view class="right-btn" hover-class="tap-hover" @click="submit()">确认</view>
				</view>
			</view>
		</view>
	</uni-popup>
 </template>
 
 <script>
	import { validateIDCard, validatePhoneNumber } from '../../common/utils'
	import requestConfig from '../../network/config'
	import { useUserStore } from '../../store/userStore'
 	export default {
 		data() {
			const currentDate = this.getDate({
				format: true
			})
 			return {
				petId:0,
				sexArr: ['GG', 'MM'],
				petTypes: [{
						text: '狗狗',
						value: 1
					},
					{
						text: '猫猫',
						value: 2
					},
				],
				neuterTypes: [{
						text: '未绝育',
						value: 1
					},
					{
						text: '已绝育',
						value: 2
					},
				],
				userStore: useUserStore(),
 				formData: {
					id:0,
					type:1,
					nickname: '',
					birthday: '请选择日期',
					sex: '',
					breeds: '',
					weight: '',
					neuter_status: 1,
					desc: '',
					pet_imgs:[],
					invite_code:'',
				},
				images: [], // 图片临时路径
				business_cert_img: '',
				auth_id: 0,
				sexIndex:'',
				isEdit: false, // 是否是编辑
				// checkBg: `url(${requestConfig.imageUrl}x5j_file/static/check-bg.png)`,
				checkBg: `url(${requestConfig.imageUrl}x5j_file/2025-03-05/174116483567c81123ea4b6.png)`,
 			}
 		},
		computed: {
			btnDisabled() {
				let b = false
				for (let key in this.formData) {
					if (this.formData.hasOwnProperty(key)) {
						let keyArr = ['nickname','sex','neuter_status'];
						if(keyArr.includes(key)) {
							if (!this.formData[key]) {
								b = true
							}
						}
						// if (key!="id" && key!="invite_code") {
						// 	if (!this.formData[key]) {
						// 		b = true
						// 	}
						// }
					}
				}
				return b
			},
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			},
		},
		// watch: {
		//     'formData.weight'(newVal) {
		// 		console.log(newVal)
		// 		newVal = String(newVal)
		// 			.replace(/[^\d.]/g, '')
		// 			.replace(/\.(?=.*\.)/g, '')
		// 			.replace(/^\./, '0.')
		// 			.replace(/^0+(?=\d)/, '')
		// 			.replace(/^(\d*)(?:\.(\d{0,2})).*$/, (m, i, d) => (i || '0') + (typeof d !== 'undefined' ? '.' + d : ''))
		// 		this.formData.weight = newVal;
		// 		console.log(newVal)
		//   //     // 可以在这里添加额外的逻辑，比如验证或转换数据
		//   //     if (newVal !== null && newVal < 0) { // 例如，不允许负数
		//   //       this.formData.weight = 0; // 重置为0或进行其他处理
		//   //     }
		//     }
		//   },
		onLoad(options) {
			if (options.petId) {
				this.petId = options.petId;
				this.getDetail();
		    }
			if (options.inviteCode) {
				this.formData.invite_code = options.inviteCode;
			}
		},
 		methods: {
		 onWeightInput(event) {
			  let newValue = event.target.value;
		
			  // 允许数字、小数点，且小数点最多出现一次
			  const numericRegex = /^-?\d*\.?\d*$/;
		
			  if (newValue === '' || numericRegex.test(newValue)) {
				// 输入值是空字符串，或者符合数字格式
				if (newValue === '') {
				  this.formData.weight = 0; // 如果输入为空，则赋值为0
				} else {
				  this.formData.weight = Number(newValue); // 转换为数字
				}
			  } else {
				// 输入值不符合数字格式，强制赋值为0
				this.formData.weight = 0;
				// 为了防止用户输入了非法字符后，input 的值还是保留非法状态
				// 这里我们可以手动将 input 的 value 设置为我们想要的值
				event.target.value = this.formData.weight;
			  }
		
			  //console.log('New weight value:', this.formData.weight);
			},
			async getDetail() {
				const res = await this.$request.get('/api/pet/detail',{
					pet_id: this.petId,
				})
				if (res.code == 200) {
					this.formData.id = res.data.id;
					this.formData.type = res.data.type;
					this.formData.nickname = res.data.nickname;
					this.formData.birthday = res.data.birthday;
					this.formData.sex = res.data.sex;
					this.formData.breeds = res.data.breeds;
					this.formData.weight  = res.data.weight;
					this.formData.neuter_status = res.data.neuter_status;
					this.formData.desc = res.data.desc;
					this.formData.pet_imgs = res.data.imgs;
					for(var i =0; i<res.data.imgs.length; i++) {
						this.images.push({
							url: res.data.imgs[i],
							fail: false,
							progress: 100
						})
					}
					
				}else{
					uni.showToast({
						title: '获取信息失败',
						icon: 'none'
					})
					return
				}
			},
			//返回
			goBack() {
				let pages = getCurrentPages();
				 if (pages.length > 1) {
					 uni.navigateBack({
					 	delta: 1,
					 });
				 }else{
					 uni.switchTab({
					 	url: '/pages/index/index'
					 });
				 }
			},
			bindPickerChange: function(e) {
				this.formData.sex =  Number(e.detail.value) +1
				this.sexIndex = e.detail.value
			},
			bindDateChange: function(e) {
				this.formData.birthday = e.detail.value
			},
			// bindTimeChange: function(e) {
			// 	this.time = e.detail.value
			// },
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year -30;
				} else if (type === 'end') {
					year = year;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// 添加图片
			addImage() {
				const count = 9 - this.images.length
				uni.chooseMedia({
					count: count,
					mediaType: ['image'],
					success: async (res) => {
						let temp = []
						const oldLength = this.images.length
						const tempFilePaths = res.tempFiles
						for await (const item of tempFilePaths) {
							if (item.size / 1024 / 1024 > 10) {
								uni.showToast({
									title: '图片不能超过10MB',
									icon: 'none'
								})
							} else {								
								temp.push(item.tempFilePath)
								this.images.push({
									url: item.tempFilePath,
									fail: false,
									progress: 0
								})
							}
						}
						if (temp == false) {
							return
						}
						let j = 0
						for await (let item of temp) {
							try {
								const res = await this.$request.upload('/api/file/upload', {
									filePath: item
								}, {
									load: false,
								}, (progress) => {
									this.images[j + oldLength].progress = progress
								})
								if (res.code == 200) {
									this.formData.pet_imgs.push(res.data.url)
									this.images[j + oldLength].fail = false
									this.images[j + oldLength].progress = 100
								} else {
									this.images[j + oldLength].fail = true
									this.images[j + oldLength].progress = 0
								}
							} catch {
								this.images[j + oldLength].fail = true
								this.images[j + oldLength].progress = 0
							}
							j += 1
						}
					}
				})
			},
			// 删除图片
			delImage(index) {
				this.images.splice(index, 1)
				this.formData.pet_imgs.splice(index, 1)
			},
			check() {
				this.$refs.checkPopup.open()
			},
 			imageChange(images) {
				this.formData.business_cert_img = images != false ? images[0] : ''
			},
			async submit() {
				if (this.formData.nickname.length == 0) {
					uni.showToast({
						title: '请填写宠物名称',
						icon: 'none'
					})
					return
				}
				// if (this.formData.birthday.length == 0) {
				// 	uni.showToast({
				// 		title: '请选择日期',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				if (!this.formData.sex) {
					uni.showToast({
						title: '请选择性别',
						icon: 'none'
					})
					return
				}
				// if (this.formData.breeds.length == 0) {
				// 	uni.showToast({
				// 		title: '请填写宠物品种',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				// if (this.formData.weight.length == 0) {
				// 	uni.showToast({
				// 		title: '请输入宠物体重',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				this.formData.weight = Number(this.formData.weight);
				const res = await this.$request.post('api/pet/create', this.formData)
				if (res.code == 200) {
					let text= this.formData.id ==0 ? "档案创建成功" : "档案更新成功";
					let that = this;
					uni.showToast({
						title: text,
						icon: 'none',
						success() {
							that.$refs.checkPopup.close();
							uni.navigateTo({
								url: '/pages/cwdn/index'
							});
						}
					});
				}
			},
			// 获取商户认证详情
			async getShopDetail() {
				const res = await this.$request.get('api/merchant_cert/detail')
				if (res.code == 200) {
					const data = res?.data || {}
					this.auth_id = data?.id || 0
					for (let key in this.formData) {
						if (this.formData.hasOwnProperty(key)) {
							this.formData[key] = data[key]
						}
					}
				}
			}
 		}
 	}
 </script>
 <style>
 page {
 	background-image: url(https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/cwdn_bg.png);
 	background-size: 100% auto;
 	background-repeat: no-repeat;
 	background-color:#FFF;
 }
 </style>
 <style scoped lang="scss">
	 .fixed-footer{
		 border-top: 1px solid rgba(0, 0, 0, 0.1);
	 }
 	.cwdn-container {
		width: 100%;
		//padding: 16rpx 30rpx;
		//padding-bottom: 200rpx;
		.dn-head {
			position: relative;
			width: 100%;
			height:130rpx;
			background-image: url(https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/cwdn-head.png);
			background-size: 100% auto;
			background-repeat: no-repeat;
			z-index:2;
			margin-top:260rpx;
		    .dn-tag{
				position: absolute;
				width: 76rpx;
				height: 66rpx;
				background-image: url(https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/cwdn-tag.png);
				background-size: 100% auto;
				background-repeat: no-repeat;
				z-index:1;
				left: 72rpx;
				top:-64rpx;
			}
		}
		.form-container{
			width: 100%;
			height:1900rpx;
			background-color: #fff;
			position: relative;
			.form-box{
				position: absolute;
				z-index: 99;
				width: 638rpx;
				//height: 1900rpx;
				margin:0 auto;
				background-color: none;
				top:-120rpx;
				left:56rpx;
				margin-bottom: 40rpx;
				padding-bottom: 200rpx;
				.form-item1{
					
				}
				.form-item {
					overflow: hidden;
					border-bottom: 1px solid rgba(0, 0, 0, 0.1);
					.name {
						width: 120rpx;
						height: 38rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 500;
						font-size: 30rpx;
						color: #333333;
						text-align: left;
						font-style: normal;
						text-transform: none;
					}
					.note {
						font-size: 28rpx;
						color: #999;
					}
					.ipt {
						margin-top:32rpx;
						width: 622rpx;
						text-align: left;
						font-weight: 400;
						font-size: 26rpx;
						color: #7B7B7B;
						font-style: normal;
						text-transform: none;
						padding-bottom: 16rpx;
					}
					
					.radio-list {
						display: grid;
						grid-template-columns: 1fr 1fr 1fr;
						row-gap: 20rpx;
						column-gap: 20rpx;
						padding-bottom: 5px;
						
					
						.radio-item {
							height: 60rpx;
							border-radius: 8px;
							background-color: #f6f6f6;
							border: 0.5px solid #f6f6f6;
							font-size: 28rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							margin-top:32rpx;
					
							.radio-mark {
								width: 24rpx;
								height: 24rpx;
								border-radius: 50%;
								display: flex;
								justify-content: center;
								align-items: center;
								border: 1px solid #999;
								margin-right: 8rpx;
							}
						}
					
						.radio-active {
							background-color: rgba($color: $uni-color-primary, $alpha: 0.1);
							border-color: $uni-color-primary;
					
							.radio-mark {
								background-color: $uni-color-primary;
								border-color: $uni-color-primary;
							}
						}
					}
					
					.text-area-wrapper {
						position: relative;
						width: 100%;
					
						.text-placeholder {
							position: absolute;
							top: 0;
							left: 0;
							right: 0;
							padding: 20rpx;
							font-size: 26rpx;
							color: #7B7B7B;;
							white-space: pre-line;
							word-wrap: break-word;
						}
					}
					.desc {
						width: 100%;
						box-sizing: border-box;
						margin-top: 32rpx;
						border: 1px solid $uni-border-color;
						border-radius: 20rpx;
						height: 300rpx;
						font-size: 28rpx;
						padding: 12rpx 20rpx;
					}
					
					.images-list {
						display: grid;
						grid-template-columns: 1fr 1fr 1fr;
						row-gap: 20rpx;
						column-gap: 20rpx;
						margin-top:32rpx;

						.add-btn {
							height: 208rpx;
							border-radius: 30rpx;
							background-color: #f6f6f6;
							overflow: hidden;
							display: flex;
							align-items: center;
							justify-content: center;
						}

						.img-wrapper {
							height: 208rpx;
							border-radius: 30rpx;
							// overflow: hidden;
							position: relative;

							.del-ico {
								position: absolute;
								top: 0;
								right: 0;
								z-index: 3;
							}

							.img {
								width: 100%;
								height: 100%;
								border-radius: 30rpx;
							}

							.percent-mask {
								position: absolute;
								top: 0;
								left: 0;
								right: 0;
								bottom: 0;
								background-color: rgba(0, 0, 0, .5);
								display: flex;
								justify-content: center;
								align-items: center;
								color: #fff;
								z-index: 2;
								border-radius: 30rpx;
							}
						}

					}
					
				}
			}
		}
		
		
		
		.auth-desc {
			font-size: 26rpx;
			color: #7B7B7B;
			line-height: 44rpx;
		}
		.form-item{
			padding-top: 24rpx;
		}
		.ipt-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0 40rpx;
			font-size: 30rpx;
			border-bottom: 1px solid rgba(0, 0, 0, 0.1);
			.name {
				font-weight: 500;
			}
			.ipt {
				width: calc(100% - 210rpx);
				text-align: right;
				color: #444;
				font-size: 28rpx;
			}
		}
		.top-distance {
			padding-top: 40rpx;
		}
		.no-border {
			border-bottom: none;
		}
		.upload-item {
			margin-top: 40rpx;
			.name {
				font-size: 30rpx;
				font-weight: 500;
				margin-bottom: 30rpx;
			}
		}
	}
	.popup-content {
		width: 632rpx;
		height: 1088rpx;
		background-image: url(https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/cwdn-add-pop.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;
		padding: 190rpx 30rpx 0;
		.close-btn{
			position:absolute;
			width: 32rpx;
			height: 32rpx;
			background-image: url(https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/cwdn-close-bg.png);
			background-size: 100% 100%;
			background-repeat: no-repeat;
			right:30rpx;
			top:30rpx;
		}
		.info-wrapper {
			width: 100%;
			.check-white {
				width: 100%;
			}
			.info {
				background-color: #fff;
				width: 100%;
				padding: 0 30rpx;
				position: relative;
				height: 694rpx;
				overflow: hidden;
				margin-top: -20rpx;
				border-radius: 0 0 24rpx 24rpx;
				padding-bottom: 30rpx ;
				.desc{
					width: 504rpx;
					height: 120rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #7B7B7B;
					line-height: 39rpx;
					text-align: left;
					font-style: normal;
					text-transform: none;
					margin:0 auto;
					margin-top: -30rpx;
					overflow: hidden;
				}
				.info-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-bottom: 38rpx;
					.name {
						font-size: 26rpx;
						font-weight: 500;
					}
					.text {
						font-size: 24rpx;
						color: #7B7B7B;
						text-align: right;
					}
				}
			}
			
			.btn-wrapper {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 40rpx;
				font-size: 32rpx;
				.left-btn {
					width: 250rpx;
					height: 72rpx;
					text-align: center;
					line-height: 72rpx;
					border: 3rpx solid $uni-color-primary;
					border-radius: 36rpx;
					color: $uni-color-primary;
				}
				.right-btn {
					width: calc(100% - 276rpx);
					height: 72rpx;
					text-align: center;
					line-height: 72rpx;
					background-color: $uni-color-primary;
					border-radius: 36rpx;
					color: #fff;
				}
			}
		}
	}
	.go-back{
		position: fixed;
		width:100%;
		height: 88rpx;
		overflow: hidden;
		z-index:999;
		top:88rpx;
		.back-icon{
			width: 64rpx;
			height: 64rpx;
			background-image: url(https://xwj-miniprogram.oss-cn-hangzhou.aliyuncs.com/static/images/back.png);
			background-size: 100% 100%;
			float: left;
			margin-left:18rpx;
			margin-top:16rpx;
		}
		.title{
			width: 500rpx;
			height: 42rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 34rpx;
			line-height: 42rpx;
			color: #000000;
			text-align: center;
			font-style: normal;
			text-transform: none;
			float: left;
			margin-top:28rpx;
			overflow: hidden;
		}
	}
 </style>